﻿using System.Windows;
using eLearning.Model;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using System.Net;
using System;
using System.Text;

namespace eLearning.MahasiswaView
{
    public partial class NilaiKuliahPage : PhoneApplicationPage
    {
        private Perkuliahan kuliah;

        public NilaiKuliahPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(RssItemPage_Loaded);
        }

        private void RssItemPage_Loaded(object sender, RoutedEventArgs e)
        {
            if (PhoneApplicationService.Current.State.ContainsKey(Config.KULIAH))
            {
                kuliah = (Perkuliahan)PhoneApplicationService.Current.State[Config.KULIAH];
            }

            if (kuliah != null)
            {
                GetNilaiQuiz(kuliah);
            }
        }


        private void GetNilaiQuiz(Perkuliahan kuliah)
        {
            string url = string.Format("{0}&{1}", Config.Instance.PERKULIAHAN_SERVICE_URL() + Config.VIEW_BY_FILTER_KEY, Guid.NewGuid().ToString());
            string json = JsonConvert.SerializeObject(kuliah);

            Uri uri = new Uri(url, UriKind.Absolute);
            WebClient webClient = new WebClient();

            webClient.Encoding = Encoding.UTF8;
            webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
            webClient.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(getNilaiQuiz_UploadStringCompleted);
            try
            {
                webClient.UploadStringAsync(uri, "POST", json);
            }
            catch (Exception) { }
        }

        private void getNilaiQuiz_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                PerkuliahanList list = JsonConvert.DeserializeObject<PerkuliahanList>(e.Result);

                if (list.Count > 0)
                {
                    textKuliah.Text = list[0].DetMatkul.Matkul.ToString();
                    textUAS.Text = list[0].UAS.ToString();
                    textUTS.Text = list[0].UTS.ToString();
                    textTugas.Text = list[0].Tugas.ToString();
                    textQuiz.Text = list[0].Quiz.ToString();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void backButton_Click(object sender, EventArgs e)
        {
            NavigationService.GoBack();
        }

    }
}